<?php
require_once '../app/Mage.php';
require_once '../lib/Varien/Io/File.php';
set_time_limit(0);
ini_set('memory_limit','2048M');
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
//getimages();
define('TEMP_TABLE','temp_etilizeimage_spr');
define('FRESH_INSTALL',false);


function p($ar,$ex=1)
{
	echo "<pre>";
	print_r($ar);
	if($ex==1) exit;
}
function m($obj,$ex=1)
{
	echo "<pre>";
	print_r(get_class($obj));
	print_r(get_class_methods(get_class($obj)));
	if($ex==1) exit;
}

class EtilizeImageDownload
{
	protected $_appId;
	protected $_url;
	protected $_batchLimit = 50;
	protected $_prod_attribs = array();
	protected $_destinationPath;
	public $logFile = 'EtilizeImage.log';
	public $logMsg = array();

	public $sql;
	public $connect;
	public $total;
	public $start;
	public $entityTypeId;
	protected $_store;
	protected $_imageGalleryType = array('Top','Bottom','Front','Rear','Large','Left','Right','Jack-Pack','Original');


	public function __construct()
	{
		$this->_appId = Mage::getStoreConfig('managecatalogspr/price_file/spex_app_id');
		$this->_url = 'http://ws.spexlive.net/service/rest/catalog?method=getProduct&appId='.$this->_appId.'&skuNumberType=SP%20Richards&skuNumberVal={sku}&catalog=na&skuTypes=all&resourceType=all&descriptionTypes=all';
		//$this->_destinationPath = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath().'/etilizeimage/';
		$this->_destinationPath = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath().'/';
		$con = Mage::getSingleton('core/resource')->getConnection('core_write');
		$this->dbConnectNormal($con->getConfig());
		$this->entityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
		$this->_store = Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);


		//Clean log file
		if(file_exists(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile)) {
			//unlink(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile);
		}
		$this->init();
	}
	public function closeConnection()
	{
		mysql_close($this->connect);
		unset($this);
	}
	public function init()
	{
		$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
		$this->prod_attribs['name'] = $installer->getAttribute('catalog_product', "name");
		$this->prod_attribs['e_etilize_pid'] = $installer->getAttribute('catalog_product', "e_etilize_pid");
		$this->prod_attribs['media_gallery'] = $installer->getAttribute('catalog_product', "media_gallery");
		$this->prod_attribs['image'] = $installer->getAttribute('catalog_product', "image");
		$this->prod_attribs['small_image'] = $installer->getAttribute('catalog_product', "small_image");
		$this->prod_attribs['thumbnail'] = $installer->getAttribute('catalog_product', "thumbnail");

		unset($installer);
		//$name = $this->getLeftJoin('name');
		//$e_etilize_pid = $this->getLeftJoin('e_etilize_pid');

		if(FRESH_INSTALL) {
			$sql = "
				DROP TABLE IF EXISTS `".TEMP_TABLE."`;
				CREATE TABLE IF NOT EXISTS `".TEMP_TABLE."` (
				  `id` int(10) NOT NULL AUTO_INCREMENT,
				  `product_id` int(10),
				  `sku` varchar(25),
				  `status` int(1) NOT NULL DEFAULT '0',
				  `message` text,
				  PRIMARY KEY (`id`),
				  KEY `sku` (`sku`,`status`)
				) ENGINE=MyISAM DEFAULT CHARSET=latin1;
				
				INSERT INTO `".TEMP_TABLE."` (`product_id`, `sku`)
				SELECT distinct(`e`.`entity_id`), `e`.`sku` 
					FROM `catalog_product_entity` AS `e` ORDER BY e.entity_id ASC ";
			$this->Query($sql);

		}else {
			$sql = "INSERT INTO `".TEMP_TABLE."` (`product_id`, `sku`)
				SELECT distinct(`e`.`entity_id`), `e`.`sku` 
					FROM `catalog_product_entity` AS `e`
					LEFT JOIN  `".TEMP_TABLE."` As `temp` ON `temp`.product_id =  `e`.`entity_id` 
					WHERE `e`.`entity_id` IS NOT NULL AND `temp`.product_id IS NULL
					ORDER BY e.entity_id ASC ";
			$this->Query($sql);
		}
        
        $imageId = $this->getAttrributeId('small_image');
        $updateQuery="UPDATE `".TEMP_TABLE."` SET `status`= 0
						where `product_id` in(SELECT `entity_id` FROM `catalog_product_entity_varchar` WHERE
						`attribute_id`=".$imageId." and `value`='')";
		$this->Query($updateQuery);	
        
		$from = " FROM `".TEMP_TABLE."` WHERE status='0' ORDER BY id ASC ";
		$this->sql = "SELECT * ".$from;

		/*
		 $this->sql = "SELECT distinct(`e`.`entity_id`), "
		 .$name['select']. $e_etilize_pid['select']
		 ." `e`.`sku`";
		 $from = " FROM `catalog_product_entity` AS `e` "
		 .$name['join']
		 .$e_etilize_pid['join']
		 ." WHERE `_table_e_etilize_pid`.`value` IS NOT NULL
			AND `_table_e_etilize_pid`.`value` != ''
			ORDER BY e.entity_id ASC ";
			*/

		$res = $this->select("SELECT count(*) AS total ". $from);
		$this->total = $res[0]['total'];

	}
    
    public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}
    
	public function dbConnectNormal($dbArray)
	{
		$connect=mysql_connect($dbArray['host'],$dbArray['username'],$dbArray['password']);
		if (!$connect) {
			die('Could not connect: ' . mysql_error());
		}
		$db_selected = mysql_select_db($dbArray['dbname'],$connect);
		if (!$db_selected) {
			die ('Database Not Connected : ' . mysql_error());
		}
		mysql_set_charset("utf8",$connect);
		mysql_query($dbArray['initStatements'],$connect);
		$this->connect = $connect;
	}
	public function Select($sql)
	{
		try {
			$res = mysql_query($sql);

			while($row = mysql_fetch_assoc($res))
			{
				$result[] = $row;
			}
			mysql_free_result($res);
			return $result;
		}catch (Exception $e) {
			$this->logMsg[] = "Query Fail:".$sql. $e->getMessage();
		}
	}
	public function Query($sqlMultiple)
	{
		try {
			foreach (explode(";", $sqlMultiple) as $sql) {
				if(!mysql_query($sql)) {
					$this->logMsg[] = mysql_error();
				};
			}
		}catch (Exception $e) {
			$this->logMsg[] = "Query Fail:".$sql. $e->getMessage().mysql_error();
		}
	}
	public function writeLog($sku)
	{
		$message = '';
		if(count($this->logMsg) > 0) {
			if(is_array($this->logMsg)) {
				foreach ($this->logMsg as $msg) {
					$message .= "No.#: ".($this->start+1).": ".$msg;
				}
				//Mage::log($message, 7, $this->logFile);
			}
		}
		$this->Query("UPDATE ".TEMP_TABLE." SET status='1', message = '".$message."' WHERE sku = '".$sku."'");
		$this->logMsg = array();
	}
	public function getLeftJoin($code,$conditions = '')
	{
		if(!isset($this->prod_attribs[$code]['backend_type']) || !isset($this->prod_attribs[$code]['attribute_id'])) {
			die($code.' - Attribute not Exist');
		}
		$type 	= $this->prod_attribs[$code]['backend_type'];
		$id 	= $this->prod_attribs[$code]['attribute_id'];




		$str['join'] = "
			LEFT JOIN `catalog_product_entity_".$type."` AS `_table_".$code."` ON (_table_".$code.".entity_id = e.entity_id) 
							AND (_table_".$code.".attribute_id='".$id."') 
							AND (_table_".$code.".store_id=0) ";
		$str['select'] = " `_table_".$code."`.`value` AS `".$code."`, ";


		return $str;
	}
	public function getImageName($product,$view)
	{
		$str = strtolower(preg_replace("/[^a-zA-Z0-9]/", "-", $product['name']) ."-".$view);
		return $str;
	}
	public function getPath($imgName)
	{
		if($imgName!='') {
			return substr($imgName,0,1)."/".substr($imgName,1,1)."/";
		}else {
			return false;
		}
	}
	public function saveProductImages($codes, $image, $product,$typeImg)
	{
		foreach ($codes as $code) {
				
			$type 	= $this->prod_attribs['media_gallery']['backend_type'];
			$id 	= $this->prod_attribs['media_gallery']['attribute_id'];


			//if($code == 'media_gallery') {
			$result = $this->select("SELECT value_id FROM catalog_product_entity_media_gallery
				WHERE `attribute_id` = '".$id."' 
					AND `entity_id` = '".$product['product_id']."'
					AND `value` = '".$image."'");
			if(isset($result[0]['value_id'])) {
				$value_id = $result[0]['value_id'];
			}else {
				$this->Query("INSERT INTO catalog_product_entity_media_gallery
				(`attribute_id` , `entity_id`, `value`) 
				VALUES ('$id', '".$product['product_id']."', '$image')");
				$value_id = mysql_insert_id();
			}

			if(isset($value_id)) {
				$name = preg_replace("/[^a-zA-Z0-9\s]/", " ", $product['name']). " - ".ucwords($typeImg). " view ";
				/*if($typeImg == 'thumbnail' || $typeImg == '300' ) {
				 $disabled = 1;
					} else {
					}
					*/
				$disabled = 0;
				$this->Query("REPLACE INTO catalog_product_entity_media_gallery_value
				(value_id, store_id, `label`,   `position`,   `disabled`) 
				VALUES ('".$value_id."', '".$this->_store->getStore()->getId()."', 
				'".$name."', '".$product['pos']."', '".$disabled."')");
			}
			//}else {
				
			//$array = array("image","thumbnail","small_image");
			if(in_array($code, array('thumbnail', 'small_image', 'image'))) {
				$type 	= $this->prod_attribs[$code]['backend_type'];
				$id 	= $this->prod_attribs[$code]['attribute_id'];

				//thumbnail, small_image, image
				$this->Query("REPLACE INTO catalog_product_entity_varchar
			(`entity_type_id`, `attribute_id`,`store_id`,`entity_id`,`value`) 
			VALUES ( '".$this->entityTypeId."','".$id."', '".$this->_store->getStore()->getId()."', '".$product['product_id']."', '".$image."')");
			}
		}
	}
	public function storeImage($product)
	{
		$varien=new Varien_Io_File();
		$id=$product['e_etilize_pid'];
		try
		{
			$url = str_replace('{sku}',$product['sku'],$this->_url);
			$client=new Zend_Http_Client($url);
			$client->setHeaders('Content-Type:text/xml');
			$response=$client->request()->getBody();

			$xml=new SimpleXMLElement($response);

			//product name
			$desc = $xml->descriptions->description;
			for($k=0;$k<count($desc);$k++) {
				if($desc[$k]['type']==2) {
					$product['name'] = (string) htmlentities($desc[$k], ENT_QUOTES, "utf-8" );
				}
			}

			//image
			$temp = $xml->resources->resource;
			for($i=0;$i<count($temp);$i++) {
				try {
					$type=(string) $temp[$i]->attributes()->type;
					//$status=$temp[$i]->attributes()->status;

					$product['pos'] = ($i+1);
					$code = array();
					if($type == "Thumbnail") {
						$code = array("thumbnail","small_image");
					}else if($type == "300") {
						$code[] = "image";
					}else  if(in_array($type,$this->_imageGalleryType)) {
						$code[] = "media_gallery";
					}else {
						continue;
					}

					// 	Store image into particular folders
					$imgName = $this->getImageName($product,$type).".jpg";
					$ShortPath= $this->getPath($imgName); //.$type."/";
					$varien->checkAndCreateFolder($this->_destinationPath.$ShortPath);
					$putcontent=$this->_destinationPath.$ShortPath.$imgName;


					/*
					 $xmlpage = file_get_contents($temp[$i]->attributes()->url);
					 header('Content-Type:image/jpeg');
					 file_put_contents($putcontent,$xmlpage);
					 */



					// initialize the class

					$image = new GetImage;
					// just an image URL
					$image->source = $temp[$i]->attributes()->url;
					$image->save_to = $this->_destinationPath.$ShortPath; // with trailing slash at the end
					$image->newName = $imgName;
					$msg = $image->download('http'); // using GD

					$this->saveProductImages($code, $ShortPath.$imgName, $product,$type);

					$this->logMsg[] = "Success: ".$product['sku']. " :=> ".$putcontent;

				}catch(exception $e) {
					$this->logMsg[] = "Fail: ".$product['sku']. $e->getMessage();
				}
			}
		} catch(exception $e) {
			$this->logMsg[] = "Fail: ".$product['sku']. $e->getMessage();
			//echo "<b>".$e->getMessage()."</b>";
			//exit;
		}
	}
	public function process()
	{
		$this->start = 0;
		while ($this->start < $this->total) {
			$Products = $this->Select($this->sql. " LIMIT 0 , ".$this->_batchLimit);
			foreach($Products as $Product) {
				$this->storeImage($Product);
				$this->writeLog($Product['sku']);
				$this->start++;
				
				/*if($this->start%5000==0) {
					//reindex
					$this->reIndexAll();
				}*/
				
			} 
		}
		$this->closeConnection();
		$this->reIndexAll();
		//$this->reindex(true);
	}
	public function reindex($all=false)
	{
		//  clear 'clear_images_cache':
	 
			//Truncate table core_flag
		
		$this->query("TRUNCATE table core_flag");
	 // IMAGE CACHE
		
		
		try {
			Mage::getModel('catalog/product_image')->clearCache();
			$this->logMsg[] =  'Image cache was cleared succesfuly' . "\n";
		}
		catch (Mage_Core_Exception $e) {
			$this->logMsg[] =  $e->getMessage() . "\n";
		}
		try {
			/*
			$flag = Mage::getModel('catalogindex/catalog_index_flag')->loadSelf();
			if ($flag->getState() == Mage_CatalogIndex_Model_Catalog_Index_Flag::STATE_RUNNING) {
				$kill = Mage::getModel('catalogindex/catalog_index_kill_flag')->loadSelf();
				$kill->setFlagData($flag->getFlagData())->save();
			}

			$flag->setState(Mage_CatalogIndex_Model_Catalog_Index_Flag::STATE_QUEUED)->save();
			Mage::getSingleton('catalogindex/indexer')->plainReindex();
			$this->logMsg[] =  'Layered Navigation Indices were refreshed successfully' . "\n";
			*/
			ob_start();
			/*
			if($all) {
				$this->logMsg[] = system('php '.Mage::getBaseDir().'/shell/indexer.php --reindexall');
			}else {
			}
			*/
			$this->logMsg[] = system('php '.Mage::getBaseDir().'/shell/indexer.php --reindex catalog_product_attribute,catalog_product_flat');
			ob_end_clean();
			
		}
		catch (Mage_Core_Exception $e) {
			$this->logMsg[] =  $e->getMessage() . "\n";
		}
		catch (Exception $e) {
			$this->logMsg[] =  'Error while refreshed Layered Navigation Indices. Please try again later' . "\n".$e->getMessage();
		}
	}
	public function reIndexAll()
    {
		//$this->query("TRUNCATE table core_flag");
        $indexterPath=Mage::getBaseDir()."/shell/indexer.php";
		Mage::app()->cleanCache();
		Mage::getModel('catalog/product_image')->clearCache();
		if(file_exists($indexterPath)){  
				system("php ".$indexterPath." --reindex catalog_product_attribute,catalog_product_flat");
        }
		Mage::app()->cleanCache();
    }
}

class GetImage {

	var $source;
	var $save_to;
	var $set_extension;
	var $quality;
	var $newName;

	function download($method = 'curl') // default method: cURL
	{
		$info = @GetImageSize($this->source);
		$mime = $info['mime'];

		if(!$mime) {
			return 'Could not obtain mime-type information. Make sure that the remote file is actually a valid image.';
		}

		// What sort of image?
		$type = substr(strrchr($mime, '/'), 1);
		$new_image_ext='';
		switch ($type) {
			case 'jpeg':
				$image_create_func = 'ImageCreateFromJPEG';
				$image_save_func = 'ImageJPEG';
				$new_image_ext = 'jpg';

				// Best Quality: 100
				$quality = isSet($this->quality) ? $this->quality : 100;
				break;

			case 'png':
				$image_create_func = 'ImageCreateFromPNG';
				$image_save_func = 'ImagePNG';
				$new_image_ext = 'png';

				// Compression Level: from 0  (no compression) to 9
				$quality = isSet($this->quality) ? $this->quality : 0;
				break;

			case 'bmp':
				$image_create_func = 'ImageCreateFromBMP';
				$image_save_func = 'ImageBMP';
				$new_image_ext = 'bmp';
				break;

			case 'gif':
				$image_create_func = 'ImageCreateFromGIF';
				$image_save_func = 'ImageGIF';
				$new_image_ext = 'gif';
				break;

			case 'vnd.wap.wbmp':
				$image_create_func = 'ImageCreateFromWBMP';
				$image_save_func = 'ImageWBMP';
				$new_image_ext = 'bmp';
				break;

			case 'xbm':
				$image_create_func = 'ImageCreateFromXBM';
				$image_save_func = 'ImageXBM';
				$new_image_ext = 'xbm';
				break;
					
			default:
				$image_create_func = 'ImageCreateFromJPEG';
				$image_save_func = 'ImageJPEG';
				$new_image_ext = 'jpg';
		}

		if($new_image_ext!='') {
			$ext = strrchr($this->source, ".");
			$strlen = strlen($ext);
			$new_name .= $this->newName; //.'.'.$new_image_ext;
		} else {
			$new_name = basename($this->source);
		}

		$image_create_func = strtolower($image_create_func);
		$image_save_func = strtolower($image_save_func);


		$save_to = $this->save_to.$new_name;

		if($method == 'curl') {
			$save_image = $this->LoadImageCURL($save_to);
		} elseif($method == 'gd') {
			$img = $image_create_func($this->source);

			if(isSet($quality)) {
				$save_image = $image_save_func($img, $save_to, $quality);
			} else {
				$save_image = $image_save_func($img, $save_to);
			}
		}elseif($method=='http') {
			$xmlpage = file_get_contents($this->source);
			header('Content-Type:image/jpeg');
			file_put_contents($save_to,$xmlpage);
		}

		return $save_image;
	}


	function LoadImageCURL($save_to)
	{
		$ch = curl_init($this->source);
		$fp = fopen($save_to, "wb");

		// set URL and other appropriate options
		$options = array(CURLOPT_FILE => $fp,
		CURLOPT_HEADER => 0,
		CURLOPT_FOLLOWLOCATION => 1,
		CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)

		curl_setopt_array($ch, $options);

		$save = curl_exec($ch);
		curl_close($ch);
		fclose($fp);

		return $save;
	}
	
}


$obj = new EtilizeImageDownload();
$obj->process();
//$obj->reIndexAll();
//$obj->storeImage(array('sku'=>'BC6238','e_etilize_pid'=>'1011441651'));
